<template>
  <div class="app-container">
    <el-form
      v-show="showSearch"
      ref="queryForm"
      :model="queryParams"
      size="small"
      :inline="true"
      label-width="90px"
    >
      <el-form-item label="任务名称" prop="taskName">
        <el-input
          v-model="queryParams.taskName"
          placeholder="请输入任务名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="任务类型" prop="jobType">
        <el-select
          v-model="queryParams.jobType"
          placeholder="请选择任务类型"
          clearable
        >
          <el-option
            v-for="dict in dict.type.appraise_tasktype"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="任务状态" prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择任务状态"
          clearable
        >
          <el-option
            v-for="dict in dict.type.taskstatus"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索</el-button>
        <el-button
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['console:tasks:add']"
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['console:tasks:edit']"
          >修改</el-button
        >
      </el-col> -->
      <el-col :span="1.5">
        <el-button
          v-hasPermi="['console:tasks:remove']"
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
        >删除</el-button>
      </el-col>
      <!-- <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['console:tasks:export']"
          >导出</el-button
        >
      </el-col> -->
      <right-toolbar
        :show-search.sync="showSearch"
        @queryTable="getList"
      />
    </el-row>

    <el-table
      v-loading="loading"
      :data="tasksList"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" align="center" />
      <el-table-column label="序号" align="center" width="55">
        <template slot-scope="scope">
          <span v-text="getIndex(scope.$index)" />
        </template>
      </el-table-column>
      <el-table-column label="任务编号" width="75" prop="id" align="center" />
      <el-table-column label="任务名称" align="center" prop="taskName" />
      <el-table-column label="任务模式" align="center" prop="taskType" />
      <el-table-column label="任务类型" align="center" prop="jobType">
        <template slot-scope="scope">
          <div v-for="dict in dict.type.all_tasktype" :key="dict.value">
            <!-- {{ dict.value ==  ? dict.label : "" }} -->
            {{ dict.value == scope.row.jobType ? dict.label : "" }}
          </div>
        </template>
      </el-table-column>

      <!-- <el-table-column label="s" align="center" prop="taskType" /> -->
      <el-table-column label="实例名" align="center" prop="dataSourceName">
        <template slot-scope="scope">
          <el-tooltip
            v-if="
              scope.row.dataSourceName && scope.row.dataSourceName.length > 12
            "
            class="item"
            effect="dark"
            :content="scope.row.dataSourceName"
            placement="top-start"
          >
            <p class="text-overflow">{{ scope.row.dataSourceName }}</p>
          </el-tooltip>
          <span v-else>{{ scope.row.dataSourceName }}</span>
        </template>
      </el-table-column>
      <el-table-column label="任务状态" align="center" prop="taskStatus">
        <template slot-scope="scope">
          <span v-for="dict in dict.type.taskstatus" :key="dict.value">
            <el-tag
              v-if="scope.row.taskStatus == dict.value"
              :type="dict.raw.listClass"
            >
              {{ dict.label }}
            </el-tag>
          </span>
        </template>
      </el-table-column>
      <el-table-column label="创建人" align="center" prop="createBy" />
      <el-table-column label="更新时间" align="center" prop="updateTime" />
      <el-table-column
        label="操作"
        align="center"
        width="120px"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <!-- <el-button
            size="mini"
            type="text"
            @click="handleScheduler(scope.row)"
            v-hasPermi="['console:dataTaskconf:scheduler']"
            >启动调度器</el-button
          > -->
          <el-button
            v-if="scope.row.taskStatus != 0"
            v-hasPermi="['console:dataTaskconf:execute']"
            size="mini"
            type="text"
            style="color: #42d885"
            @click="handleExecute(scope.row)"
          >执行</el-button>
          <el-button
            v-hasPermi="['console:tasks:result']"
            size="mini"
            type="text"
            @click="handleResult(scope.row)"
          >记录</el-button>
          <el-button
            v-hasPermi="['console:tasks:resultLog']"
            size="mini"
            type="text"
            @click="handleNewResult(scope.row)"
          >结果</el-button>
          <el-button
            v-hasPermi="['console:tasks:resultLog']"
            size="mini"
            type="text"
            @click="handleResultLog(scope.row)"
          >日志</el-button>
          <el-button
            v-hasPermi="['console:tasks:edit']"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-hasPermi="['console:tasks:remove']"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pgNum"
      :limit.sync="queryParams.pgSize"
      @pagination="getList"
    />

    <!-- 添加或修改评估任务对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="任务名称" prop="taskName">
          <el-input v-model="form.taskName" placeholder="请输入任务名称" />
        </el-form-item>
        <el-form-item label="任务类型" prop="taskType">
          <el-input v-model="form.taskType" placeholder="请输入任务类型" />
        </el-form-item>
        <el-form-item label="数据源ID" prop="id">
          <el-input v-model="form.id" placeholder="请输入数据源ID" />
        </el-form-item>
        <el-form-item label="数据库名称" prop="databaseName">
          <el-input
            v-model="form.databaseName"
            placeholder="请输入数据库名称"
          />
        </el-form-item>
        <el-form-item label="对象类型" prop="taskWay">
          <el-input v-model="form.taskWay" placeholder="请输入对象类型" />
        </el-form-item>
        <el-form-item label="统计信息" prop="taskCount">
          <el-input v-model="form.taskCount" placeholder="请输入统计信息" />
        </el-form-item>
        <el-form-item label="统计模块" prop="taskMode">
          <el-input v-model="form.taskMode" placeholder="请输入统计模块" />
        </el-form-item>
        <el-form-item label="执行策略" prop="strategy">
          <el-input v-model="form.strategy" placeholder="请输入执行策略" />
        </el-form-item>
        <el-form-item label="描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入描述" />
        </el-form-item>
        <el-form-item label="描述" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            placeholder="请输入内容"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="评估日志"
      :before-close="handleClose"
      :visible.sync="isLog"
      width="45%"
      destroy-on-close
    >
      <div style="margin-bottom: 10px">
        <el-progress :percentage="taskProgress" status="success" />
      </div>
      <div v-show="logFofText.length > 0" ref="logBox" class="textBox">
        <p
          v-for="(item, index) in logFofText"
          :key="index"
          :style="{ color: item.logLevel == 'error' ? 'red' : false }"
        >
          {{ item.text }}
        </p>
      </div>
      <el-empty
        v-show="logFofText.length < 1"
        description="暂无日志"
      />

      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="handleEnter">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  listTasks,
  getTasks,
  delTasks,
  addTasks,
  updateTasks,
  dataTaskconfScheduler,
  dataTaskconfExecute,
  dataTaskLogGetInfo,
  dataTaskLogExecute,
  dataTaskLogGetNew,
  dataTaskLogGetNewLog
} from '@/api/console/tasks'
import Vue from 'vue'

export default {
  name: 'Tasks',
  dicts: ['taskstatus', 'appraise_tasktype', 'all_tasktype'],
  beforeRouteEnter(to, from, next) {
    next((vm) => {
      vm.getList()
      vm.listTimer = setInterval(() => {
        vm.getList()
      }, 3000)
    })
  },
  beforeRouteLeave(to, from, next) {
    clearInterval(this.listTimer)
    this.listTimer = null
    next()
  },
  data() {
    return {
      fullscreenLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 评估任务表格数据
      tasksList: [],
      // 弹出层标题
      title: '',
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pgNum: 1,
        pgSize: 10,
        taskName: null,
        taskType: null,
        jobType: null,
        taskStatus: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {},
      isLog: false,
      logFofText: [],
      timer: null,
      listTimer: null,
      taskProgress: 0
    }
  },
  methods: {
    getTaskProgress(data) {
      const taskProgress = JSON.parse(data)
      let progress = 0
      Object.keys(taskProgress).forEach((f) => {
        if (f == 'total') return
        const { current, total } = taskProgress[f]
        const progressTotal = 100 / taskProgress.total
        if (current == total) {
          progress += progressTotal
        } else {
          progress += progressTotal * (current / total)
        }
      })
      return Math.floor(progress)
    },
    getIndex($index) {
      return (
        (this.queryParams.pgNum - 1) * this.queryParams.pgSize + $index + 1
      )
    },
    async handleNewResult(row) {
      if (row.taskStatus != 2) {
        return this.$message.warning('任务未成功')
      }
      const res = await dataTaskLogGetNew({
        jobType: row.jobType,
        taskId: row.id
      })
      window.open(`/report/assessmentReport?id=${res.data.id}`)
    },
    async handleResultLog(row) {
      this.isLog = true
      this.logFofText = []
      const that = this
      this.taskProgress = 0
      let res = await dataTaskLogGetNew({
        jobType: row.jobType,
        taskId: row.id
      })
      const logText = JSON.parse(res.data.taskLog)
      logText.forEach((f) => {
        this.logFofText.push({
          text: `${f.time}：${f.logMsg}`,
          logLevel: f.logLevel
        })
      })
      this.$nextTick(() => {
        const scrollElem = that.$refs.logBox
        scrollElem.scrollTo({
          top: scrollElem.scrollHeight,
          behavior: 'smooth'
        })
      })
      if (res.data.taskStatus == 0 || res.data.jobType == 'SYNC_DATA') {
        that.timer = setInterval(async() => {
          res = await dataTaskLogGetNewLog({
            id: res.data.id
          })
          if (res.data.taskStatus != 0) {
            clearInterval(that.timer)
            that.timer = null
            const res = await dataTaskLogGetNew({
              jobType: row.jobType,
              taskId: row.id
            })
            this.taskProgress = this.getTaskProgress(res.data.taskProgress)
            const logText = JSON.parse(res.data.taskLog)
            logText.forEach((f, i) => {
              if (f.logMsg.includes(logText[i])) return
              this.logFofText.push({
                text: `${f.time}：${f.logMsg}`,
                logLevel: f.logLevel
              })
            })
            this.$nextTick(() => {
              const scrollElem = that.$refs.logBox
              scrollElem.scrollTo({
                top: scrollElem.scrollHeight,
                behavior: 'smooth'
              })
            })
            return
          }
          this.taskProgress = this.getTaskProgress(res.data.taskProgress)
          JSON.parse(res.data.taskLog).forEach((f) => {
            this.logFofText.push({
              text: `${f.time}：${f.logMsg}`,
              logLevel: f.logLevel
            })
          })
          this.$nextTick(() => {
            const scrollElem = that.$refs.logBox
            scrollElem.scrollTo({
              top: scrollElem.scrollHeight,
              behavior: 'smooth'
            })
          })
        }, 1000)
      } else {
        this.taskProgress = this.getTaskProgress(res.data.taskProgress)
        clearInterval(this.timer)
        this.timer = null
        return
      }
    },
    handleClose() {
      this.isLog = false
      this.logFofText = []
      clearInterval(this.timer)
      this.timer = null
    },
    /** 查询评估任务列表 */
    async getList() {
      this.loading = false
      listTasks(this.queryParams).then(async(response) => {
        this.tasksList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    // 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        taskName: null,
        taskType: null,
        id: null,
        databaseName: null,
        taskWay: null,
        taskCount: null,
        taskMode: null,
        taskTables: null,
        taskStatus: null,
        strategy: null,
        desc: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        remark: null
      }
      this.resetForm('form')
    },
    handleEnter() {
      clearInterval(this.timer)
      this.timer = null
      this.isLog = false
      return
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pgNum = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.$router.push({ path: '/steps/stepsIndex' })
      this.title = '添加评估任务'
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.title = '修改评估任务'
      this.$router.push({
        path: '/steps/stepsIndex',
        query: { id: row.id || this.ids }
      })
    },
    // 评估报告按钮
    handleResult(row) {
      this.$router.push({
        path: '/reports/index',
        query: { id: row.id, jobType: row.jobType, type: 'reports' }
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.id != null) {
            updateTasks(this.form).then((response) => {
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addTasks(this.form).then((response) => {
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      let ids = row.id || this.ids
      if (Object.prototype.toString.call(ids) !== '[object Array]') {
        ids = [ids]
      }
      this.$modal
        .confirm('是否确认删除评估任务编号为"' + ids + '"的数据项？')
        .then(function() {
          return delTasks({ idArray: ids })
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {})
    },
    handleScheduler(row) {
      const that = this
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认启动调度器？').then(function() {
        dataTaskconfScheduler({
          id
        })
          .then((res) => {
            that.$message.success('调度器启动成功')
          })
          .catch((err) => {
            that.$message.error('调度器启动失败')
          })
      })
    },
    handleExecute(row) {
      const that = this
      const ids = row.id || this.ids
      this.$modal.confirm('是否确认立即执行？').then(function() {
        const loading = that.$loading({
          lock: true,
          text: '执行中',
          spinner: 'el-icon-loading',
          background: 'rgba(0, 0, 0, 0.7)'
        })
        dataTaskLogExecute({
          id: ids
        })
          .then((res) => {
            loading.close()
            that.getList()
            that.$message.success('任务提交成功')
          })
          .catch((err) => {
            loading.close()
            that.getList()
            that.$message.error('执行失败')
          })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.textBox {
  height: 300px;
  overflow-y: auto;
}

.text-overflow {
  overflow: hidden; /* 确保超出容器的文本被裁剪 */
  white-space: nowrap; /* 确保文本在一行内显示 */
  text-overflow: ellipsis; /* 使用省略号表示文本超出 */
}
</style>
